package org.example.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.example.common.base.constants.AuthConstant;
import org.example.common.redis.service.RedisService;
import org.example.system.dao.SysResourceDao;
import org.example.system.dao.SysRoleDao;
import org.example.system.dao.SysRoleResourceDao;
import org.example.system.entity.SysResource;
import org.example.system.entity.SysRole;
import org.example.system.entity.SysRoleResource;
import org.example.system.service.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色 服务实现类
 * </p>
 *
 * @author LiJunYi
 * @since 2020-05-25
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleDao, SysRole> implements ISysRoleService
{
    @Value("${spring.application.name}")
    private String applicationName;

    @Autowired
    SysRoleDao roleDao;
    @Autowired
    RedisService redisService;
    @Autowired
    SysResourceDao resourceDao;
    @Autowired
    SysRoleResourceDao roleResourceDao;

    /**
     * 获取角色通过用户id
     *
     * @param id id
     * @return {@link List}<{@link SysRole}>
     */
    @Override
    public List<SysRole> getRolesByUserId(Long id) {
        return roleDao.getRolesByUserId(id);
    }

    /**
     * 初始化资源角色Map集合
     *
     * @return {@link Map}<{@link String}, {@link List}<{@link String}>>
     */
    @Override
    public Map<String, List<String>> initResourceRolesMap() {
        Map<String,List<String>> resourceRoleMap = new TreeMap<>();
        List<SysResource> resourceList = resourceDao.getAllResourceList();
        List<SysRole> roleList = roleDao.getAllRoleList();
        List<SysRoleResource> relationList = roleResourceDao.getAllRoleResourceList();
        for (SysResource resource : resourceList) {
            // 获取当前资源所有能访问的角色信息
            Set<Integer> roleIds = relationList.stream().filter(item -> item.getResourceId().equals(resource.getId())).map(SysRoleResource::getRoleId).collect(Collectors.toSet());
            // 获取当前资源所有能访问的角色名称，ID_名称 形式
            List<String> roleNames = roleList.stream().filter(item -> roleIds.contains(item.getId())).map(item -> item.getId() + "_" + item.getName()).collect(Collectors.toList());
            // 资源与角色的对应关系
            resourceRoleMap.put("/"+applicationName+resource.getUrl(),roleNames);
        }
        redisService.deleteObject(AuthConstant.RESOURCE_ROLES_MAP_KEY);
        redisService.setCacheMap(AuthConstant.RESOURCE_ROLES_MAP_KEY,resourceRoleMap);
        return resourceRoleMap;
    }
}
